/*
 * JSF Toolkit Component Framework
 * Copyright (C) 2007 Noah Sloan <iamnoah A-T gmail D0T com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 */
package com.jsftoolkit.utils;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Returns the results of a series of iterators, in the order they were provided
 * to the constructor.
 * 
 * @author noah
 * 
 * @param <T>
 */
public class ConcatenatedIterator<T> implements Iterator<T> {

	private final Iterator<? extends T>[] iterators;

	private int lastReturned;

	private int next;

	public ConcatenatedIterator(final Iterator<? extends T>... iterators) {
		super();
		this.iterators = iterators;
	}

	public boolean hasNext() {
		boolean result = next < iterators.length && iterators[next].hasNext();
		while (!result && next < iterators.length - 1) {
			result = iterators[++next].hasNext();
		}
		return result;
	}

	public T next() {
		// find the next iterator with an element
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		return iterators[lastReturned = next].next();
	}

	public void remove() {
		iterators[lastReturned].remove();
	}

}
